package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.system.domain.fx.FxGoodclassify;
import com.ruoyi.system.excelTemplate.Product;
import com.ruoyi.common.pub.util.ImportExcelUtil;
import com.ruoyi.system.mapper.fx.FxGoodclassifyMapper;
import com.ruoyi.system.service.ExcelImportService;
import com.ruoyi.system.service.fx.IFxGoodclassifyService;
import com.ruoyi.system.service.impl.fxImpl.FxGoodclassifyServiceImpl;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ExcelImportServiceImpl implements ExcelImportService {
    @Resource
    private FxGoodclassifyMapper fxGoodclassifyMapper;

    @Override
    public void importProduct(MultipartFile file, String pictruePath) throws Exception {
        List<FxGoodclassify> fxGoodclassifies = fxGoodclassifyMapper.selectFxGoodclassifyList(new FxGoodclassify());
        Map<String, FxGoodclassify> nameMapping = new HashMap<>();
        Map<Long, List<FxGoodclassify>> pIdMapping = new HashMap<>();
        Optional.ofNullable(fxGoodclassifies).orElse(new ArrayList<>()).forEach(el -> {
            nameMapping.put(el.getDeptName() + "-" + el.getParentId(), el);
            pIdMapping.compute(el.getParentId(), (k, v) -> {
                if (v == null) {
                    List<FxGoodclassify> list = new ArrayList<>();
                    list.add(el);
                    return list;
                }
                v.add(el);
                return v;
            });
        });
        ImportExcelUtil.importExcel(file.getInputStream(), new Product(), products -> {
            products.forEach(el -> {
                FxGoodclassify first = nameMapping.get(el.getFirCategory() + "-0");
                if (first == null) {
                    first = create(nameMapping, pIdMapping, 0, "0", 0L, el.getFirCategory());
                    fxGoodclassifyMapper.insertFxGoodclassify(first);
                }
                FxGoodclassify second = nameMapping.get(el.getSecCategory() + "-" + first.getId());
                if (second == null) {
                    second = create(nameMapping, pIdMapping, 1, first.getAncestors() + "," + first.getId(), first.getId(), el.getSecCategory());
                    fxGoodclassifyMapper.insertFxGoodclassify(second);
                }
                FxGoodclassify prod = nameMapping.get(el.getProdName() + "-" + second.getId());
                if (prod == null) {
                    prod = create(nameMapping, pIdMapping, 2, second.getAncestors() + "," + second.getId(), second.getId(), el.getProdName());
                    fxGoodclassifyMapper.insertFxGoodclassify(prod);
                }
                String fileName = StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                        prod.getDeptName(), Seq.getId(Seq.uploadSeqType), "jpg");
                FileInputStream fis = null;
                FileOutputStream fos = null;
                String filePath = RuoYiConfig.getUploadPath();
                String url = Constants.RESOURCE_PREFIX+"/upload/" + fileName;
                try {
                    fis = new FileInputStream(pictruePath + "/" + prod.getDeptName() + ".jpg");
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    try {
                        File targetFile = new File(filePath+  "/" + fileName);
                        if (!targetFile.exists()) {
                            if (!targetFile.getParentFile().exists()) {
                                targetFile.getParentFile().mkdirs();
                            }
                        }
                        fos = new FileOutputStream(targetFile);
                        while ((len = fis.read(bytes)) != -1) {
                            fos.write(bytes, 0, len);
                        }
                        FxGoodclassify fxGoodclassify = new FxGoodclassify();
                        fxGoodclassify.setId(prod.getId());
                        fxGoodclassify.setClassifyImg(url);
                        fxGoodclassifyMapper.updateFxGoodclassify(fxGoodclassify);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                } catch (IOException e) {
                    return;
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        });
    }

    private FxGoodclassify create(Map<String, FxGoodclassify> nameMapping, Map<Long, List<FxGoodclassify>> pIdMapping, int tier, String ancestors, Long parentId, String deptName) {
        FxGoodclassify fxGoodclassify = new FxGoodclassify();
        fxGoodclassify.setParentId(parentId);
        fxGoodclassify.setAncestors(ancestors);
        fxGoodclassify.setTier(tier);
        fxGoodclassify.setDeptName(deptName);
        List<FxGoodclassify> list = pIdMapping.get(parentId);
        if (list == null) {
            fxGoodclassify.setSort(1L);
        } else {
            list.sort((o1, o2) -> o2.getSort().compareTo(o1.getSort()));
            fxGoodclassify.setSort(list.get(0).getSort() + 1);
        }
        nameMapping.put(deptName + "-" + parentId, fxGoodclassify);
        FxGoodclassify finalFxGoodclassify = fxGoodclassify;
        pIdMapping.compute(fxGoodclassify.getParentId(), (k, v) -> {
            if (v == null) {
                List<FxGoodclassify> list1 = new ArrayList<>();
                list1.add(finalFxGoodclassify);
                return list1;
            }
            v.add(finalFxGoodclassify);
            return v;
        });
        return finalFxGoodclassify;
    }
}
